
const _plate = require('./_plate.json');
const _cache = require('./_cache.json');

// process.on('message', (m) => {
//     if (m === 'exit') {
//         process.exit(0);
//     }
// });

(() => {
    const _list = process.argv[2];
    let list = [];
    try {
        list = JSON.parse(_list);
    } catch (err) {
        process.stderr.write('list 参数异常');
        process.exit(1);
    }

    let queue = [];
    for (const item of _cache[list[0]]) {
        queue = [{ ...item }];
        calc(list, queue, _plate, _cache, 1);
        if (queue.length === 11) break;
    }

    const log = queue.map(v => v.path?.[0]);
    process.stdout.write(JSON.stringify(log));
})();

function calc(keys, queue, plate, cache, level) {
    const name = keys[level];
    const list = cache[name];
    const len = queue.length;
    // console.log('--->', name, level, list.length);
    // console.log(name, level, len, list[25]);

    const maxRow = 7;
    const maxCol = 8;

    // console.log(JSON.stringify(list));

    let index = -1;
    for (const item of list) {
        index++;
        let isItemOk = true;
        
        for (let i=0; i<maxRow; i+=1) {
            let isRowBreak = false;

            for (let j=0; j<maxCol; j+=1) {
                let isColBreak = false;

                if (plate[i][j] === 1) continue;
                if (item.plate[i][j] !== 1) continue;

                // if (i === 1 && j === 3 && name === 'NO4') console.log('--->', index, queue.length);

                for (const v of queue) {
                    if (v.plate[i][j] === 1) {
                        isColBreak = true;
                        break;
                    }
                }

                if (isColBreak) {
                    isRowBreak = true;
                    break;
                }
            }

            if (isRowBreak) {
                isItemOk = false;
                break;
            }
        }

        if (isItemOk) {
            const k = queue.map(v => {
                const { i, j, k } = v.path[0];
                return `${i}_${j}_${k}`;
            }).join('|');
            if (item._del?.[k]) return false;

            queue.push(item);
            if (level < 10) {
                const isDone = calc(keys, queue, plate, cache, level+1);
                // console.log('--->', name, isDone, level, index, k);

                if (!isDone) {
                    _item = queue.pop();
                    _item._del = { [k]: 1 };
                }
            }
        }
    }

    if (queue.length === 11) return true;
    return !(len === queue.length);
}